﻿Imports System.IO
Imports System.Data
Imports VSModel
Imports Cls_Common

Partial Class Control_Customer_ListAdmin
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "regjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "regjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If

            txtTitleFilter.Text = Now.Date.ToString("dd/MM/yyyy")
            BindToGrid(1, txtTitleFilter.Text)
            btnExport.Attributes.Add("onclick", "return confirmMultiDelete('" & btnExport.ClientID & "');")
        End If
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1, Optional ByVal strSearch As String = "")
        Using data As New VSEntities
            'So ban ghi muon the hien tren trang
            ' Dim _HotelId As Integer = Session("HotelId")
            Dim _FromDate As Date = StringToDate(txtTitleFilter.Text)
            Dim _ToDate As Date = _FromDate.AddDays(1)

            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            Dim p = (From q In data.Customers Where q.Created >= _FromDate And q.Created < _ToDate _
                                                Order By q.CustomerId Descending Select q).Skip((iPage - 1) * intPag_Size).Take(intPag_Size).ToList

            Dim strKey_Name() As String = {"CustomerId", "FullName", "HotelId"}
            'Tong so ban ghi
            hidCount.Value = (From q In data.Customers Where q.Created >= _FromDate And q.Created < _ToDate Order By q.CustomerId Descending Select q.CustomerId).Count
            Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        BindToGrid(lnkTile.ToolTip)
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region
#Region "Event for control"


    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1
            ' Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
            ' lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
            'Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            'hplEdit.NavigateUrl = MainDomain & "chinh-sua-thong-tin-khach-" & grdShow.DataKeys(e.Row.RowIndex)("CustomerId").ToString & ".html"
            Dim hplFullname As HyperLink = CType(e.Row.FindControl("hplFullname"), HyperLink)
            ' hplFullname.NavigateUrl = MainDomain & "chi-tiet-thong-tin-khach-" & grdShow.DataKeys(e.Row.RowIndex)("CustomerId").ToString & ".html"
            hplFullname.Text = grdShow.DataKeys(e.Row.RowIndex)("FullName").ToString
        End If
    End Sub
#End Region
#Region "Search"
    Protected Sub btnFilter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFilter.Click
        BindToGrid(1, txtTitleFilter.Text.Trim())
    End Sub
#End Region

    Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
        Dim str As New StringBuilder
        Dim strInsert As String = "INSERT INTO DBTT_TMP (HTVIET,NGTHNSINH,GTINH,XD_NTNSINH,MAQT,VIETNAM,SO_HC, SO_TT,NGHENGHIEP,MAMD, NGAY_NHAP_CANH,MACK,HANXUAT,NGAYDEN,NGAYDI,CQDON, MAKS, NGAYNHAPMAY) VALUES"
        Dim st As String = ""
        Dim _FromDate As Date = StringToDate(txtTitleFilter.Text)
        Dim _ToDate As Date = _FromDate.AddDays(1)
        Dim strFileExpoxt As String = ""
        Using _data As New VSEntities

            ' With Response
            '    .AddHeader("Content-disposition", "attachment;filename=" & txtTitleFilter.Text & ".tx")
            '    .ContentType = "application/octet-stream"

            'End With
            Response.ContentType = "application/octet-stream"
            '   Response.Charset = ""
            Response.AddHeader("Content-Disposition", "attachment;filename=" & txtTitleFilter.Text & ".txt")
            Response.ContentEncoding = Encoding.UTF8
            '  Response.BinaryWrite(Encoding.Unicode.GetPreamble())



            Dim p = (From q In _data.Customers Where q.Created >= _FromDate And q.Created < _ToDate Order By q.CustomerId Descending Select q).ToList
            For Each y In p
                str = New StringBuilder()

                st = ""
                str.Append(strInsert)

                '    strValues = customer.FullName & "," & customer.DateOfBirth & customer.Sex & customer.DateOfBirthType & customer.CountryCode & customer.Object & customer.PasspostNumber _
                '                 & customer.TemporaryResidenceCard & customer.Career & customer.EntryPurposeCode & customer.EntryDate & customer.GateCode & customer.ExpiredDate & customer.

                st = st & "('" & y.FullName & "',"
                st = st & "'" & CType(y.DateOfBirth, Date).ToString("dd/MM/yyyy") & "',"
                st = st & "'" & IIf(y.Sex = 1, "M", "F") & "',"
                st = st & "'" & y.DateOfBirthType & "',"
                st = st & "'" & y.CountryCode & "',"
                st = st & "'" & IIf(y.Object = "Người nước ngoài", 1, 0) & "',"

                st = st & "'" & y.PasspostNumber & "',"
                st = st & "'" & y.TemporaryResidenceCard & "',"
                st = st & "'" & y.Career & "',"
                st = st & "'" & y.EntryPurposeCode & "',"
                st = st & "'" & CType(y.EntryDate, Date).ToString("dd/MM/yyyy") & "',"
                st = st & "'" & y.GateCode & "',"
                If Not y.ThoiHanThiThuc Is Nothing Then
                    st = st & "'" & CType(y.ThoiHanThiThuc, Date).ToString("dd/MM/yyyy") & "',"
                Else
                    st = st & "'" & CType(y.ExpiredDate, Date).ToString("dd/MM/yyyy") & "',"
                End If

                st = st & "'" & CType(y.FromDate, Date).ToString("dd/MM/yyyy") & "',"
                st = st & "'" & CType(y.ToDate, Date).ToString("dd/MM/yyyy") & "',"
                st = st & "'" & y.AgencyWelcome & "',"
                st = st & "'" & y.Hotel.HotelCode & "',"
                st = st & "'" & CType(y.Created, Date).ToString("dd/MM/yyyy") & "')"
                str.Append(st)
                str.Append(vbNewLine)
                Response.Write(str.ToString() & vbCrLf)
                Response.Flush()
            Next

            'oWrite.Close()

            Response.End()

        End Using




    End Sub
End Class
